import axios, { AxiosAdapter } from 'axios';
import Toast from '@c/toast/Toast.tsx';
import local from '@/utils/local';

const baseUrl = 'http://192.168.31.40:3000';

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    console.log('请求拦截', config);
    config.headers.authorization = local.get('token');
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    console.log('响应拦截', response);
    if (response.status === 200 && response.data.code === 1) {
      return response.data;
    }
    Toast({ text: response.data.data, type: 'error' }); // 提示
    return { code: -1, data: response.data.data };
  },
  error => {
    // 对响应错误做点什么
    console.log('接口响应错误', error);
    Toast({ type: 'error', text: '请求错误，请检查接口地址或者网络' });
    return Promise.reject(error);
  }
);

export const postLogin = baseUrl + '/login'; // 登录

export const postEmailCode = baseUrl + '/login/getCode'; // 获取邮箱验证码

interface Request {
  post: Function;
  get: Function;
}

const reuqest: Request = {
  post: (obj: AxiosAdapter) => {
    return axios({ method: 'post', ...obj });
  },
  get: (obj: AxiosAdapter) => {
    return axios({ method: 'get', ...obj });
  },
};

export default reuqest;
